<template>
    <div v-if="dataDisplay !== null" style="overflow-x: auto;overflow-y: hidden;" @mouseup="config.mouseUp()"
        @mousemove="(e) => config.mousemove(e)" @mouseenter="config.mouseUp()">
        <div style="height: 100%;display: inline-block;position: relative;font-size: 14px;border-top: 1px solid rgb(200,200,200);"
            :style="{
                width: `${config.getCurrentTotalWidth()}px`,
                marginRight: '40vw'
            }">
            <div
                style="width: 100%;height: 25px;display: flex;justify-content: flex-start;align-items: center;background-color: rgb(242,242,242);">
                <div v-if="dataDisplay.enableSelect"
                    style="display: inline-block;border-right: 1px solid rgb(200,200,200);height: 100%;" :style="{
                        width: `${config.selectWidth}px`
                    }">
                    <div
                        style="width: 100%;height: 100%;display: flex;justify-content: flex-start;align-items: center;padding: 0 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;">
                        <cIcon style="cursor: pointer;" @click="dataDisplay.callBack({
                            op: 'unselectAll'
                        })" v-if="(() => {
                            for (let i = 0; i < dataDisplay.list.length; i++) {
                                if (!dataDisplay.list[i]._selected) return false
                            }
                            return true
                        })()" color="rgb(0,120,215)" name="selected"></cIcon>
                        <cIcon style="cursor: pointer;" @click="dataDisplay.callBack({
                            op: 'selectAll'
                        })" v-if="!(() => {
                            for (let i = 0; i < dataDisplay.list.length; i++) {
                                if (!dataDisplay.list[i]._selected) return false
                            }
                            return true
                        })()" name="unselected"></cIcon>
                    </div>
                </div>
                <div v-if="config.getOpWidth()"
                    style="display: inline-block;border-right: 1px solid rgb(200,200,200);height: 100%;" :style="{
                        width: `${config.getOpWidth()}px`
                    }">
                    <div
                        style="width: 100%;height: 100%;display: flex;justify-content: flex-start;align-items: center;padding: 0 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;">
                        操作
                    </div>
                </div>
                <div v-for="(item, index) in dataDisplay.form"
                    style="display: inline-block;height: 100%;position: relative;" :style="{
                        width: `${config.getColumnWCurrentidth(item.field)}px`,
                        borderRight: '1px solid rgb(200,200,200)'
                    }">
                    <div
                        style="width: 100%;height: 100%;display: flex;justify-content: flex-start;align-items: center;padding: 0 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;">
                        <div
                            style="width: 100%;overflow: hidden;text-overflow: ellipsis;word-break: keep-all;white-space: nowrap;">
                            {{ item.title }}
                        </div>
                    </div>
                    <div @mousedown="e => config.mousedown(item.field, e)" @click="() => {
                        
                    }"
                        style="width: 4px;height: 100%;display: inline-block;position: absolute;top: 0;right: 0;transform: translateX(2px);cursor: ew-resize;">

                    </div>
                </div>
            </div>
            <div class="hideScrollbar"
                style="width: 100%;position: absolute;left: 0;bottom: 0;height: calc(100% - 25px);overflow-x: hidden;overflow-y: auto;">
                <div v-for="(item, index) in dataDisplay.list"
                    :class="`${(dataDisplay.enableSelect && item._selected) ? (index % 2 ? 'line2-selected' : 'line-selected') : (index % 2 ? 'line2' : 'line')}`"
                    :style="{
                        borderBottom: (index === dataDisplay.list.length - 1) ? '1px solid rgb(200,200,200)' : '',
                        height: (index === dataDisplay.list.length - 1) ? '26px' : '25px',
                    }" style="width: 100%;display: flex;justify-content: flex-start;align-items: flex-start;">

                    <div v-if="dataDisplay.enableSelect" style="display: inline-block;height: 100%;" :style="{
                        width: `${config.selectWidth}px`,
                        borderRight: (dataDisplay.enableSelect && item._selected) ? '1px solid rgba(255,255,255,0.2)' : ('1px solid rgb(200,200,200)')
                    }">
                        <div
                            style="width: 100%;height: 100%;display: flex;justify-content: flex-start;align-items: center;padding: 0 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;">
                            <cIcon style="cursor: pointer;" @click="dataDisplay.callBack({
                                op: 'unselect',
                                item
                            })" v-if="item._selected" color="white" name="selected"></cIcon>
                            <cIcon style="cursor: pointer;" @click="dataDisplay.callBack({
                                op: 'select',
                                item
                            })" v-if="!item._selected" name="unselected"></cIcon>
                        </div>
                    </div>
                    <div v-if="config.getOpWidth()" style="display: inline-block;height: 100%;" :style="{
                        width: `${config.getOpWidth()}px`,
                        borderRight: (dataDisplay.enableSelect && item._selected) ? '1px solid rgba(255,255,255,0.2)' : ('1px solid rgb(200,200,200)')
                    }">
                        <div :style="{
                            gap: `${config.opGap}px`
                        }"
                            style="width: 100%;height: 100%;display: flex;justify-content: flex-start;align-items: center;padding: 0 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;">
                            <span @click="() => {
                                try {
                                    dataDisplay.callBack({
                                        op: opItem.op,
                                        item: item
                                    })
                                } catch (error) {

                                }
                            }" style="transform: translateY(1px);cursor: pointer;" v-for="opItem in item.op"
                                :title="opItem.title">
                                <cIcon :name="opItem.icon"></cIcon>
                            </span>
                        </div>
                    </div>
                    <div v-for="(subItem, index2) in dataDisplay.form" @click="() => {
                        dataDisplay.callBack({
                            op: 'rowClick',
                            item
                        })
                    }" style="height: 100%;display: flex;justify-content: flex-start;align-items: center;padding-left: 5px;padding-right: 5px;word-break: keep-all;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;"
                        :style="{
                            width: `${config.getColumnWCurrentidth(subItem.field)}px`,
                            borderRight: (dataDisplay.enableSelect && item._selected) ? '1px solid rgba(255,255,255,0.2)' : ('1px solid rgb(200,200,200)')
                        }" :title="item[subItem.field]">
                        <div
                            style="width: 100%;overflow: hidden;text-overflow: ellipsis;word-break: keep-all;white-space: nowrap;">
                            <span
                                v-if="typeof (item[subItem.field]) === 'string' && item[subItem.field].startsWith('data:image')">
                                <img style="height: 20px;display: inline-block;" :src="item[subItem.field]" alt="">
                            </span>
                            <span v-else>{{ item[subItem.field] }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import tool from '../modules/tool'
import cIcon from './cIcon.vue';
import flexBox from './flexBox.vue';

const props = defineProps({
    data: {
        type: Object,
        default: {}
    }
})

const dataDisplay = ref(null)

const config = ref({
    columnWidth: {},
    currentMovingField: '',
    selectWidth: 30,
    opSpare: 8,
    opWidth: 24,
    opGap: 5,
    spareWidth: 20,
    multipleWidth: 1.6,
    init(data, f = false) {
        if (dataDisplay.value === null || f) {
            this.columnWidth = {}
            let list = data.list
            let form = data.form
            form.forEach(element => {
                let maxWidth = tool.getTextWidth(element.title, '14px') * this.multipleWidth + this.spareWidth
                list.forEach(item => {
                    let currentWidth = tool.getTextWidth(item[element.field], '14px') * this.multipleWidth + this.spareWidth
                    if (currentWidth > maxWidth) {
                        maxWidth = currentWidth
                    }
                })
                if (maxWidth > document.body.clientWidth / 2) {
                    maxWidth = maxWidth / ((maxWidth / (document.body.clientWidth / 2)) * 2)
                }
                this.columnWidth[element.field] = {
                    default: maxWidth,
                    current: maxWidth
                }
            })
        }
        dataDisplay.value = data
    },
    getColumnWCurrentidth(fieldName) {
        let width = this.columnWidth[fieldName]
        if (width === undefined) {
            return 'auto'
        }
        return width.current
    },
    resetColumnWidth(fieldName) {
        let width = this.columnWidth[fieldName]
        if (width === undefined) {
            return
        }
        width.current = width.default
    },
    getCurrentTotalWidth() {
        let re = 0
        for (let i = 0; i < Object.keys(this.columnWidth).length; i++) {
            re += this.columnWidth[Object.keys(this.columnWidth)[i]].current
        }
        if (dataDisplay.value.enableSelect) {
            re += this.selectWidth
        }
        re += this.getOpWidth()
        return re
    },
    getOpWidth() {
        if (dataDisplay.value.list) {
            let maxOperationNum = 0
            for (let i = 0; i < dataDisplay.value.list.length; i++) {
                if (dataDisplay.value.list[i].op && maxOperationNum < dataDisplay.value.list[i].op.length) {
                    maxOperationNum = dataDisplay.value.list[i].op.length
                }
            }
            if (!maxOperationNum) return 0
            if (maxOperationNum * this.opWidth + this.opSpare < 40) {
                return 40
            }
            return maxOperationNum * this.opWidth + this.opSpare
        } else {
            return 0
        }
    },
    mousedown(fieldName, e) {
        try {
            this.currentMovingField = fieldName
            this.columnWidth[this.currentMovingField].moving = true
            this.columnWidth[this.currentMovingField].lastX = e.x
        } catch (error) {

        }
    },
    mousemove(e) {
        try {
            if (!this.columnWidth[this.currentMovingField].moving) return
            let c = e.x - this.columnWidth[this.currentMovingField].lastX
            if ((this.columnWidth[this.currentMovingField].current + c) < 30) return
            this.columnWidth[this.currentMovingField].current += c
            this.columnWidth[this.currentMovingField].lastX = e.x
        } catch (error) {

        }
    },
    mouseUp() {
        try {
            this.columnWidth[this.currentMovingField].moving = false
        } catch (error) {

        }
    }
})

watch(() => props.data, (to, from) => {
    let oldForm = from.form
    let newForm = to.form
    let flag = true
    if (oldForm.length === newForm.length) {
        oldForm.forEach(item1 => {
            let oldField = item1.field
            let flag2 = false
            newForm.forEach(item2 => {
                let newField = item2.field
                if (newField === oldField) {
                    flag2 = true
                }
            })
            if (flag2 === false) {
                flag = false
            }
        })
    } else {
        flag = false
    }
    config.value.init(props.data, !flag)
    console.log(`data table data changed :`, props.data)
})

onMounted(async () => {
    config.value.init(props.data)
    console.log('data table init :', props.data)
})
</script>

<style scoped>
.line {
    background-color: white;
    transition: background-color .0.5s;
}

.line2 {
    background-color: rgb(242, 242, 242);
    transition: background-color .0.5s;
}

.line-selected {
    background-color: rgb(10, 131, 229);
    color: white !important;
    transition: background-color .0.5s;
}

.line2-selected {
    background-color: rgb(0, 120, 215);
    color: white !important;
    transition: background-color .0.5s;
}

.line:hover {
    background-color: rgba(0, 120, 215, 0.2);
}

.line2:hover {
    background-color: rgba(0, 120, 215, 0.2);
}

.line-selected:hover {
    background-color: rgb(39, 151, 243);
    color: white !important;
}

.line2-selected:hover {
    background-color: rgb(39, 151, 243);
    color: white !important;
}
</style>